package com.houxm.caipiao.service.spider;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.houxm.caipiao.model.Ssq_drawing_history;
import com.houxm.caipiao.model.Ssq_drawing_reward;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.c3p0.C3p0Plugin;

/**
 * 从中彩网获取双色球开奖号码
 * 
 * @author 学明
 *
 */
public class SsqDrawingZhcwUtil {

	public static void main(String[] args) throws Exception {
		PropKit.use("a_little_config.txt");
		C3p0Plugin c3p0Plugin = new C3p0Plugin(PropKit.get("jdbcUrl"), PropKit.get("user"),
				PropKit.get("password").trim());
		c3p0Plugin.start();
		ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
		arp.addMapping("ssq_drawing_reward", Ssq_drawing_reward.class);
		arp.start();
		int term = 2016014;
		String sql = "select * from ssq_drawing_reward where term>" + term;
		List<Ssq_drawing_reward> list = Ssq_drawing_reward.me.find(sql);
		for (Ssq_drawing_reward dr : list) {
			int tmp = dr.getInt("term");
			String str = getDataFromHtml(tmp);
			System.out.println(str);
			if (str != null)
				writeMysql(str, dr);
			// break;
		}

		// PropKit.use("a_little_config.txt");
		// C3p0Plugin c3p0Plugin = new C3p0Plugin(PropKit.get("jdbcUrl"),
		// PropKit.get("user"),
		// PropKit.get("password").trim());
		// c3p0Plugin.start();
		// ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
		// arp.addMapping("ssq_drawing_reward", Ssq_drawing_reward.class);
		// arp.start();
		// int term = 2015000;
		// String sql = "select * from ssq_drawing_reward where lvl6=0 and term<"+term+"
		// and term >"+2003000+" order by term asc";
		// List<Ssq_drawing_reward> list = Ssq_drawing_reward.me.find(sql);
		// for(Ssq_drawing_reward dr:list){
		// int tmp = dr.getInt("term");
		// String str = getDataFromHtml2(tmp);
		// System.out.println(str);
		// if(str!=null)
		// writeMysql2(str, dr);
		// break;
		// }
	}

	/**
	 * 爬取网页中的开奖信息，并记录到数据库中.
	 * 
	 * @param term
	 * @return isSuccess
	 */
	public static boolean spiderNext(int term) {
		boolean flag = false;
		try {
			String content = getDataFromHtml(term);
			flag = writeBallsAndReward(content, term);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	public static void writeMysql(String str, Ssq_drawing_reward drawing) {
		Ssq_drawing_reward dr = new Ssq_drawing_reward();
		dr.set("id", drawing.getInt("id"));
		dr.set("lvl1",
				str.substring(str.indexOf("\"ONE_Z\":\"") + 9, str.indexOf("\"", str.indexOf("\"ONE_Z\":\"") + 10)));
		dr.set("lvl1money",
				str.substring(str.indexOf("\"ONE_J\":\"") + 9, str.indexOf("\"", str.indexOf("\"ONE_J\":\"") + 10)));
		dr.set("lvl2",
				str.substring(str.indexOf("\"TWO_Z\":\"") + 9, str.indexOf("\"", str.indexOf("\"TWO_Z\":\"") + 10)));
		dr.set("lvl2money",
				str.substring(str.indexOf("\"TWO_J\":\"") + 9, str.indexOf("\"", str.indexOf("\"TWO_J\":\"") + 10)));
		dr.set("lvl3", str.substring(str.indexOf("\"THREE_Z\":\"") + 11,
				str.indexOf("\"", str.indexOf("\"THREE_Z\":\"") + 12)));
		dr.set("lvl4",
				str.substring(str.indexOf("\"FOUR_Z\":\"") + 10, str.indexOf("\"", str.indexOf("\"FOUR_Z\":\"") + 11)));
		dr.set("lvl5",
				str.substring(str.indexOf("\"FIVE_Z\":\"") + 10, str.indexOf("\"", str.indexOf("\"FIVE_Z\":\"") + 11)));
		dr.set("lvl6",
				str.substring(str.indexOf("\"SIX_Z\":\"") + 9, str.indexOf("\"", str.indexOf("\"SIX_Z\":\"") + 10)));
		Date date = drawing.getDate("lotteryDate");
		@SuppressWarnings("deprecation")
		int week = date.getDay();
		if (week == 0) {
			week = 7;
		}
		System.out.println(week);
		dr.set("lotteryWeek", week);
		dr.set("saleMoney", str.substring(str.indexOf("\"TZ_MONEY\":\"") + 12,
				str.indexOf("\"", str.indexOf("\"TZ_MONEY\":\"") + 13)));
		dr.set("poolMoney", str.substring(str.indexOf("\"JC_MONEY\":\"") + 12,
				str.indexOf("\"", str.indexOf("\"JC_MONEY\":\"") + 13)));
		dr.update();
	}

	/**
	 * 获取该期次的中奖情况的网页内容
	 * 
	 * @param term
	 * @return
	 * @throws Exception
	 */
	public static String getDataFromHtml(int term) throws Exception {
		String result = null;
		String jsonUrl = "http://app.zhcw.com/wwwroot/zhcw/jsp/kjggServ.jsp?catalogId=14609&issueNo=" + term
				+ "&jsonpcallback=?";
		URL url = new URL(jsonUrl);
		InputStream is = url.openStream();
		BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
		String str = "";
		String l = null;
		while ((l = buffer.readLine()) != null) {
			str += l;
		}
		// System.out.println(str);
		if (str.contains("\"code\":1")) {
			String id = str.substring(str.indexOf("\"id\":\"") + 6, str.indexOf("\"", str.indexOf("\"id\":\"") + 7));
			URL url1 = new URL("http://www.zhcw.com/ssq/kjgg/" + id + ".shtml");
			InputStream is2 = url1.openStream();
			BufferedReader buffer2 = new BufferedReader(new InputStreamReader(is2));
			StringBuffer str2 = new StringBuffer();
			String l2 = null;
			while ((l2 = buffer2.readLine()) != null) {
				str2.append(l2).append("\n");
				if (l2.contains("<div id=\"currentScript\" style=\"display:none;\">")) {
					result = l2.replace("<div id=\"currentScript\" style=\"display:none;\">", "").replace("</div>", "")
							.replace("&quot;", "\"").replace("&#32;", " ").trim();
					break;
				}
			}
		}
		return result;
	}

	public static String getDataFromHtml2(int term) throws Exception {
		String result = null;
		String jsonUrl = "http://app.zhcw.com/wwwroot/zhcw/jsp/kjggServ.jsp?catalogId=14609&issueNo=" + term
				+ "&jsonpcallback=?";
		URL url = new URL(jsonUrl);
		InputStream is = url.openStream();
		BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
		String str = "";
		String l = null;
		while ((l = buffer.readLine()) != null) {
			str += l;
		}
		// System.out.println(str);
		if (str.contains("\"code\":1")) {
			String id = str.substring(str.indexOf("\"id\":\"") + 6, str.indexOf("\"", str.indexOf("\"id\":\"") + 7));
			URL url1 = new URL("http://www.zhcw.com/ssq/kjgg/" + id + ".shtml");
			System.out.println(url1);
			InputStream is2 = url1.openStream();
			BufferedReader buffer2 = new BufferedReader(new InputStreamReader(is2));
			StringBuffer str2 = new StringBuffer();
			String l2 = null;
			boolean flag = false;
			while ((l2 = buffer2.readLine()) != null) {
				if (l2.contains("Winning_number")) {
					flag = true;
				}

				if (l2.contains("双色球开奖查询")) {
					break;
				}

				if (flag)
					str2.append(l2).append("\n");
				// if(l2.contains("<div id=\"currentScript\" style=\"display:none;\">")){
				// result = l2.replace("<div id=\"currentScript\" style=\"display:none;\">", "")
				// .replace("</div>", "").replace("&quot;", "\"").trim();
				// break;
				// }
			}
			result = str2.toString();
		}
		return result;
	}

	public static void writeMysql2(String str, Ssq_drawing_reward drawing) {
		Ssq_drawing_reward dr = new Ssq_drawing_reward();
		dr.set("id", drawing.getInt("id"));

		String tmp = null;
		if (str == null || !str.contains("win_result")) {
			return;
		}
		str = str.replace(" style=\"border-style: dotted; border-color: rgb(211, 211, 211);\"", "");
		str = str.replace(
				" style=\"font-family: 宋体, Arial, Verdana, sans-serif; font-size: 14px; border: 1px dotted rgb(211, 211, 211);\"",
				"");
		tmp = str.substring(str.indexOf("一等奖") + 3);
		tmp = tmp.substring(tmp.indexOf("</td>") + 5);
		String lvl1 = tmp.substring(tmp.indexOf("<td>") + 4, tmp.indexOf("</td>")).replace(",", "").trim();
		dr.set("lvl1", Integer.parseInt(lvl1));
		tmp = tmp.substring(tmp.indexOf("</td>") + 5);
		String lvl1money = tmp.substring(tmp.indexOf("<td>") + 4, tmp.indexOf("</td>")).replace(",", "").trim();
		dr.set("lvl1money", Float.parseFloat(lvl1money));

		tmp = tmp.substring(tmp.indexOf("二等奖") + 3);
		tmp = tmp.substring(tmp.indexOf("</td>") + 5);
		String lvl2 = tmp.substring(tmp.indexOf("<td>") + 4, tmp.indexOf("</td>")).replace(",", "").trim();
		dr.set("lvl2", Integer.parseInt(lvl2));
		tmp = tmp.substring(tmp.indexOf("</td>") + 5);
		String lvl2money = tmp.substring(tmp.indexOf("<td>") + 4, tmp.indexOf("</td>")).replace(",", "").trim();
		dr.set("lvl2money", Float.parseFloat(lvl2money));

		tmp = tmp.substring(tmp.indexOf("三等奖") + 3);
		tmp = tmp.substring(tmp.indexOf("</td>") + 5);
		String lvl3 = tmp.substring(tmp.indexOf("<td>") + 4, tmp.indexOf("</td>")).replace(",", "").trim();
		dr.set("lvl3", Integer.parseInt(lvl3));

		tmp = tmp.substring(tmp.indexOf("四等奖") + 3);
		tmp = tmp.substring(tmp.indexOf("</td>") + 5);
		String lvl4 = tmp.substring(tmp.indexOf("<td>") + 4, tmp.indexOf("</td>")).replace(",", "").trim();
		dr.set("lvl4", Integer.parseInt(lvl4));

		tmp = tmp.substring(tmp.indexOf("五等奖") + 3);
		tmp = tmp.substring(tmp.indexOf("</td>") + 5);
		String lvl5 = tmp.substring(tmp.indexOf("<td>") + 4, tmp.indexOf("</td>")).replace(",", "").trim();
		dr.set("lvl5", Integer.parseInt(lvl5));

		tmp = tmp.substring(tmp.indexOf("六等奖") + 3);
		tmp = tmp.substring(tmp.indexOf("</td>") + 5);
		String lvl6 = tmp.substring(tmp.indexOf("<td>") + 4, tmp.indexOf("</td>")).replace(",", "").trim();
		dr.set("lvl6", Integer.parseInt(lvl6));
		Date date = drawing.getDate("lotteryDate");
		@SuppressWarnings("deprecation")
		int week = date.getDay();
		if (week == 0) {
			week = 7;
		}
		System.out.println(week);
		dr.set("lotteryWeek", week);

		tmp = tmp.substring(tmp.indexOf("本期销售额：") + 6);
		String saleMoney = tmp.substring(0, tmp.indexOf("元")).replace(",", "").trim();
		dr.set("saleMoney", Integer.parseInt(saleMoney));

		tmp = tmp.substring(tmp.indexOf("奖池累计金额：") + 7);
		String poolMoney = tmp.substring(0, tmp.indexOf("元")).replace(",", "").trim();
		dr.set("poolMoney", Integer.parseInt(poolMoney));
		dr.update();
	}

	/**
	 * 根据传进来的中奖信息的网页内容，分析数据后保存到数据库中
	 * 
	 * @param str
	 * @param term
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static boolean writeBallsAndReward(String str, int term) throws Exception {
		if (str == null || !(str.contains("KJ_Z_NUM") && str.contains("KJ_T_NUM") && str.contains("ONE_Z")
				&& str.contains("ONE_J") && str.contains("TWO_Z") && str.contains("TWO_J") && str.contains("THREE_Z")
				&& str.contains("FOUR_Z") && str.contains("FIVE_Z") && str.contains("SIX_Z") && str.contains("KJ_DATE")
				&& str.contains("TZ_MONEY") && str.contains("JC_MONEY")))
			return false;
		Ssq_drawing_history dh = new Ssq_drawing_history();
		String reds = str.substring(str.indexOf("\"KJ_Z_NUM\":\"") + 12,
				str.indexOf("\"", str.indexOf("\"KJ_Z_NUM\":\"") + 13));
		String blue = str.substring(str.indexOf("\"KJ_T_NUM\":\"") + 12,
				str.indexOf("\"", str.indexOf("\"KJ_T_NUM\":\"") + 13));
		String[] red = reds.split(" ");
		if (red == null || red.length != 6) {
			return false;
		}
		int[] redBall = new int[6];
		for (int i = 0; i < red.length; i++) {
			redBall[i] = Integer.parseInt(red[i]);
		}

		for (int i = 0; i < redBall.length; i++) {
			for (int j = i + 1; j < redBall.length; j++) {
				if (redBall[i] > redBall[j]) {
					int a = redBall[i];
					redBall[i] = redBall[j];
					redBall[j] = a;
				}
			}
		}

		int blueBall = Integer.parseInt(blue);
		dh.set("term", term);
		dh.set("red1", redBall[0]);
		dh.set("red2", redBall[1]);
		dh.set("red3", redBall[2]);
		dh.set("red4", redBall[3]);
		dh.set("red5", redBall[4]);
		dh.set("red6", redBall[5]);
		dh.set("blue", blueBall);

		Ssq_drawing_reward dr = new Ssq_drawing_reward();
		dr.set("term", term);
		dr.set("lvl1",
				str.substring(str.indexOf("\"ONE_Z\":\"") + 9, str.indexOf("\"", str.indexOf("\"ONE_Z\":\"") + 10)));
		dr.set("lvl1money",
				str.substring(str.indexOf("\"ONE_J\":\"") + 9, str.indexOf("\"", str.indexOf("\"ONE_J\":\"") + 10)));
		dr.set("lvl2",
				str.substring(str.indexOf("\"TWO_Z\":\"") + 9, str.indexOf("\"", str.indexOf("\"TWO_Z\":\"") + 10)));
		dr.set("lvl2money",
				str.substring(str.indexOf("\"TWO_J\":\"") + 9, str.indexOf("\"", str.indexOf("\"TWO_J\":\"") + 10)));
		dr.set("lvl3", str.substring(str.indexOf("\"THREE_Z\":\"") + 11,
				str.indexOf("\"", str.indexOf("\"THREE_Z\":\"") + 12)));
		dr.set("lvl4",
				str.substring(str.indexOf("\"FOUR_Z\":\"") + 10, str.indexOf("\"", str.indexOf("\"FOUR_Z\":\"") + 11)));
		dr.set("lvl5",
				str.substring(str.indexOf("\"FIVE_Z\":\"") + 10, str.indexOf("\"", str.indexOf("\"FIVE_Z\":\"") + 11)));
		dr.set("lvl6",
				str.substring(str.indexOf("\"SIX_Z\":\"") + 9, str.indexOf("\"", str.indexOf("\"SIX_Z\":\"") + 10)));
		String kjDate = str.substring(str.indexOf("\"KJ_DATE\":\"") + 11,
				str.indexOf("\"", str.indexOf("\"KJ_DATE\":\"") + 12));
		SimpleDateFormat format3 = new SimpleDateFormat("yyyy/MM/dd");
		Date date = format3.parse(kjDate);
		int week = -1;
		if (date != null) {
			week = date.getDay();
			dr.set("lotteryDate", date);
			if (week == 0) {
				week = 7;
			}
			dr.set("lotteryWeek", week);
		}

		dr.set("saleMoney", str.substring(str.indexOf("\"TZ_MONEY\":\"") + 12,
				str.indexOf("\"", str.indexOf("\"TZ_MONEY\":\"") + 13)));
		dr.set("poolMoney", str.substring(str.indexOf("\"JC_MONEY\":\"") + 12,
				str.indexOf("\"", str.indexOf("\"JC_MONEY\":\"") + 13)));

		dh.save();
		dr.save();

		return true;
	}

}
